<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返顶效果</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .fix_box{
            width: 50px;
            height: 100px;
            background: #58bc58;
            position: fixed;
            right: 0;
            bottom: 20px;
            display: none;
            text-align: center;
            line-height: 100px;
            user-select: none;
        }
        body{
            height: 4000px;
        }
    </style>
</head>
<body>
    <div class="fix_box">toTop</div>
    <script>
        var fixBox = document.getElementsByClassName('fix_box')[0];

        // 超出显示
        window.onscroll = function(){
            // 设置滚动条滚动的长度，也可以直接用scrollY
            var toTopH = document.documentElement.scrollTop;
            // 超1000显示，反之不显示
            if(toTopH>=1000){
                fixBox.style.display = 'block';
            }else{
                fixBox.style.display = 'none';
            }
        }

        // 全局声明
        var timer;
        // 点击返顶
        fixBox.onclick = function(){

            // 每次点击前清空定时器
            clearInterval(timer);

            /* // 瞬间返顶
            window.scrollTo({top:0}); */

            // 缓慢返顶(定时器)
            timer = setInterval(function(){
                if(scrollY<=0){
                    clearInterval(timer);
                }
                scrollTo({top:scrollY-300});
            },300);
        }
    </script>
</body>
</html>